import axios from './axios/axios.min.js'

const __baseURL = 'http://127.0.0.1:8181'

// create an axios instance
const service = axios.create({
  // url = base url + request url
  // baseURL: process.env.VUE_APP_BASE_API,
  baseURL: __baseURL,
  timeout: 120000, // request timeout
  adapter: uniAdapter
})

// request interceptor
service.interceptors.request.use(
  config => {
    // config.url = tosun(config.url)

    // if (config.url !== '/login/noCode' && store.getters.token) {
    //   config.headers['Authorization'] = getToken()
    // }

    // get请求映射params参数
    if (config.method === 'get' && config.params) {
      let url = config.url + '?'
      for (const propName of Object.keys(config.params)) {
        const value = config.params[propName]
        var part = encodeURIComponent(propName) + '='
        if (value !== null && typeof (value) !== 'undefined') {
          if (typeof value === 'object') {
            for (const key of Object.keys(value)) {
              const params = propName + '[' + key + ']'
              var subPart = encodeURIComponent(params) + '='
              url += subPart + encodeURIComponent(value[key]) + '&'
            }
          } else {
            url += part + encodeURIComponent(value) + '&'
          }
        }
      }
      url = url.slice(0, -1)
      config.params = {}
      config.url = url
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(

  response => {
    const res = response.data

    // 401 处理
    //   return Promise.reject(new Error(res.msg || '401 未登录'))

    // 500 通用处理
    //   return Promise.reject(new Error(res.msg || 'Error'))

    return res

    // if (response.headers['content-type'].indexOf('excel') >= 0) {
    //   return response
    // } else if (res.code === 401) {
    //   // to re-login
    //   throw new Error("please use this in uni-app project!");
    //   return Promise.reject(new Error(res.msg || '401 未登录'))
    // }else if (res.code != 200 && res.status !== 200) {
    //   console.log( "error request" );
    //   return Promise.reject(new Error(res.msg || 'Error'))
    // } else {
    //   return res
    // }
    
  },
  error => {
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)


export default service

const request = service

export function get(url, params ){
  return request({
      url: url,
      method: 'GET',
      params: params
  })
}

export function post(url, data ){
  return request({
      url: url,
      method: 'post',
      data: data
  })
}

export function put(url, data ){
  return request({
      url: url,
      method: 'put',
      data: data
  })
}

export function del(url, data ){
  return request({
      url: url,
      method: 'delete',
      data: data
  })
}

export function download(url, data, method='post') {
  return request({
      url: url,
      method: method,
      data: data,
      responseType: 'blob'
  }).then( res => {
      let blob = new Blob([res.data])
      let headers = res.headers;
      const contentDisposition = headers['content-disposition'];
      let fileName = window.decodeURI(contentDisposition.split('filename=')[1]);

      if ('download' in document.createElement('a')) {
          let link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob); // 创建下载的链接
          link.download = fileName; // 下载后文件名
          link.style.display = 'none';
          document.body.appendChild(link);
          link.click(); // 点击下载
          window.URL.revokeObjectURL(link.href); // 释放掉blob对象
          document.body.removeChild(link); // 下载完成移除元素
      } else {
          // IE10+下载
          window.navigator.msSaveBlob(blob, fileName);
      }
  })
}

const uniAdapter = (config) => {
  if (!uni) {
    throw new Error("please use this in uni-app project!");
  }
  return new Promise((resolve, reject) => {
    const { headers, data, params } = config;
    const uniConfig = {
      ...config,
      // url: baseURL + url,
      header: headers,
    };

    if (data || params) {
      try {
        uniConfig.data = JSON.parse(data || params);
      } catch (e) {
        uniConfig.data = data || params;
      }
    }
    uni.request({
      ...uniConfig,
      success(res) {
        resolve({...res, headers: res.header });
      },
      fail(res) {
        reject({...res, headers: res.header });
      },
    });
  });
};